package com.psycho.sys.api.controller;

import com.psycho.sys.api.common.Result;
import com.psycho.sys.api.entity.User;
import com.psycho.sys.api.service.UserService;
import com.psycho.sys.api.utils.JwtUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.util.Map;

@Tag(name = "认证接口")
@RestController
@RequestMapping("/api/auth")
public class AuthController {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    private UserService userService;

    @Operation(summary = "用户登录")
    @PostMapping("/login")
    public Result<?> login(@RequestBody Map<String, String> loginRequest, HttpServletResponse response) {
        try {
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(
                    loginRequest.get("username"),
                    loginRequest.get("password"));

            Authentication authentication = authenticationManager.authenticate(authenticationToken);
            SecurityContextHolder.getContext().setAuthentication(authentication);
            String jwt = jwtUtils.generateToken(authentication.getName());

            // 创建Cookie并设置属性
            Cookie jwtCookie = new Cookie("api-token", jwt);
            jwtCookie.setMaxAge((int) jwtUtils.getExpiration());
            jwtCookie.setPath("/");
            jwtCookie.setHttpOnly(false);
            jwtCookie.setSecure(true);
            response.addCookie(jwtCookie);

            // 获取当前登录用户信息
            User currentUser = userService.findByUsername(authentication.getName());
            // 清除敏感信息
            currentUser.setPassword(null);

            return Result.success(currentUser);
        } catch (Exception e) {
            return Result.error("用户名或密码错误");
        }
    }

    @Operation(summary = "用户注册")
    @PostMapping("/register")
    public Result<?> register(@RequestBody User user) {
        // 检查用户名是否已存在
        if (userService.findByUsername(user.getUsername()) != null) {
            return Result.error("用户名已存在");
        }

        // 加密密码
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        user.setPassword(encoder.encode(user.getPassword()));

        // 设置默认值
        user.setUserType(2); // 设置为普通用户
        user.setStatus(1); // 设置为启用状态
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());

        // 保存用户
        userService.save(user);

        // 清除敏感信息
        user.setPassword(null);

        return Result.success(user);
    }
}